package com.jereh.oa.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class BaseDao {
	private Connection connection;
	private PreparedStatement pStatement;
	private ResultSet rs;
	private CallableStatement cStatement;
	public static Logger logger = Logger.getLogger(BaseDao.class);
	public void getConnection(){
		Context context;
		DataSource ds;
		try {
			context = new InitialContext();
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oa2");
			this.connection = ds.getConnection();
		} catch (NamingException e) {
			logger.debug(e.getMessage(),e);
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}		
	}
	
	public ResultSet query(String sqlStr){
		return this.query(sqlStr, null);
	}
	
	public ResultSet query(String sqlStr,List<Object> list){
		getConnection();
		try {
			pStatement = connection.prepareStatement(sqlStr);
			if(list != null){
				setParas(list);
			}
			rs = pStatement.executeQuery();
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}
		return rs;
	}	
	
	public boolean update(String sqlStr,List<Object> list){
		boolean flag = false;
		getConnection();
		try {
			pStatement = connection.prepareStatement(sqlStr);
			if(list != null){
				setParas(list);
			}
			int count = pStatement.executeUpdate();
			if(count > 0){
				flag = true;
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		} finally {
			this.close();
		}		
		return flag;
	}
	
	public boolean update(String sqlStr){
		return this.update(sqlStr, null);
	}
	
	public void close(){		
		try {
			if(cStatement!=null){
				cStatement.close();
			}
			if (rs != null) {
				rs.close();
			}
			if(pStatement != null){
				pStatement.close();
			}
			if(connection != null){
				connection.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}
	}
	
	private void setParas(List<Object> list){		
		try {
			for (int i = 0; i < list.size(); i++) {
				pStatement.setObject(i + 1, list.get(i));
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}	
	}
}
